package di.scanner.mongo.dao.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;

import di.scanner.mongo.dao.BasicDao;
import di.scanner.mongo.dao.ProviderViewDao;
import di.scanner.mongo.model.ProviderViewDI;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class ProviderViewDaoImpl extends BasicDao implements ProviderViewDao {

    private final static String TABLE_NAME = "ProviderView";
    MongoCollection<Document> collection;

    public ProviderViewDaoImpl(){
        super();
        collection = getDataBase().getCollection(TABLE_NAME);
    }


    public void save(ProviderViewDI result) {
        Document document = Document.parse(JSON.toJSONString(result));
        collection.insertOne(document);
    }

    public List<ProviderViewDI> search(){
        List<Document> documentList = new ArrayList<>();
        List<ProviderViewDI> providerViewDIList = new ArrayList<>();
        collection.find().into(documentList);
        for (Document document: documentList) {
            ProviderViewDI providerViewDI = JSONObject.parseObject(document.toJson(),ProviderViewDI.class);
            providerViewDIList.add(providerViewDI);
        }

        return providerViewDIList;
    }

    public ProviderViewDI searchByServerName(String servername){

        BasicDBObject queryCondition = new BasicDBObject();
        queryCondition.append("serviceName",servername);
        Document document = collection.find().filter(queryCondition).first();
        ProviderViewDI providerViewDI = JSONObject.parseObject(document.toJson(),ProviderViewDI.class);
        return providerViewDI;
    }
}
